package com.sinosoft.perfect.system._.util;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sinosoft.perfect.common.htmlContentType.Parse_HtmlContentType;

public class DownloadFileUtil {
	
	private String filePath;
	private String fileName;
	private HttpServletResponse response;
	private HttpServletRequest request;
	private String fileExtensions;
	private byte [] b;

	private DownloadFileUtil(){}
	
	/**
	 * 带有参数的构造方法(下载文件)
	 * 
	 * filepath为文件路径
	 * filename 下载到本地后的名称
	 * response
	 * @param filePath
	 * @param fileName
	 * @param response
	 */
	private DownloadFileUtil(String filePath,String fileName,HttpServletResponse response,HttpServletRequest request){
		this.filePath=filePath;
		this.fileName=fileName;
		this.response=response;
		this.request = request;
		this.fileExtensions=fileName.substring(fileName.lastIndexOf(".")+1);
	}
	
	public static void downloadFile(String filePath,String fileName,HttpServletResponse response,HttpServletRequest request) throws FileNotFoundException,IOException {
		DownloadFileUtil downloadFileUtil = new DownloadFileUtil(filePath,fileName,response,request);
		downloadFileUtil.generateBytes();
		downloadFileUtil.downLoad();
	}
	
	private void generateBytes() throws FileNotFoundException,IOException{
		FileInputStream fis = new FileInputStream(filePath);
		b = new byte[fis.available()];
		fis.read(b);
		fis.close();
	}

	private void downLoad() throws IOException{
		if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") >0)
			fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
		else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") >0)
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");//IE浏览器
		else
			fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
		response.reset();
		String contentType = Parse_HtmlContentType.getValue(fileExtensions);
		response.setContentType(contentType);
		//String fileNameNew =fileName.replaceAll(" ", "_");
		response.addHeader("Content-Disposition","attachment;filename=\""+ fileName+"\"");
		
		OutputStream out = response.getOutputStream();
		out.write(b);
		out.close();		
	}	
}
